import ttkbootstrap as ttk


class Column:
    def __init__(self, field, label, sortable=False):
        self.field = field
        self.label = label
        self.sortable = sortable


class GridBuilder:
    def __init__(self, root, data_model):
        self.root = root
        self.data_model = data_model
        self.columns = []
        self.main_frame = ttk.Frame(root)
        self.main_frame.pack(fill=ttk.BOTH, expand=True, padx=10, pady=10)
        self.action_classes = []
        self.tool_classes = []
        self.row_height = None
        self.title = ""

    def column(self, field, label=None, sortable=False):
        if not label:
            label = field.capitalize()
        column = Column(field, label, sortable)
        self.columns.append(column)
        return self

    def action(self, action_class):
        self.action_classes.append(action_class)
        return self

    def tool(self, tool_class):
        self.tool_classes.append(tool_class)
        return self

    def height(self, height):
        self.row_height = height
        return self

    def set_title(self, title):
        self.title = title
        return self

    def setup_ui(self):
        # 创建顶部标题和工具按钮框架
        top_frame = ttk.Frame(self.main_frame)
        top_frame.pack(fill=ttk.X, padx=5, pady=2)

        # 添加标题
        title_label = ttk.Label(top_frame, text=self.title, font=('Arial', 12, 'bold'))
        title_label.pack(side=ttk.LEFT, padx=5)

        # 添加工具按钮
        for tool_class in self.tool_classes:
            tool_text = getattr(tool_class, 'title', lambda: "工具")()
            tool_button = ttk.Button(top_frame, text=tool_text,
                                     command=lambda tc=tool_class: self.perform_tool_action(tc))
            tool_button.pack(side=ttk.RIGHT, padx=5)

        # 创建表头框架
        header_frame = ttk.Frame(self.main_frame)
        header_frame.pack(fill=ttk.X, padx=5, pady=2)

        # 显示表头
        for col in self.columns:
            label = ttk.Label(header_frame, text=col.label, font=('Arial', 10, 'bold'), anchor='center')
            label.pack(side=ttk.LEFT, padx=5, expand=True, fill=ttk.X)

        # 添加操作列表头
        action_label = ttk.Label(header_frame, text="操作", font=('Arial', 10, 'bold'), anchor='center')
        action_label.pack(side=ttk.LEFT, padx=5, expand=True, fill=ttk.X)

        # 设置表头行高
        if self.row_height is not None:
            header_frame.pack_propagate(0)
            header_frame.configure(height=self.row_height)

        # 插入用户数据
        for row_index, item in enumerate(self.data_model):
            # 创建一个框架作为列表项
            item_frame = ttk.Frame(self.main_frame)
            item_frame.pack(fill=ttk.X, padx=5, pady=2)

            # 显示每列数据
            for col in self.columns:
                value = item.get(col.field, "")
                label = ttk.Label(item_frame, text=value, anchor='center')
                label.pack(side=ttk.LEFT, padx=5, expand=True, fill=ttk.X)

            # 创建操作按钮框架
            button_frame = ttk.Frame(item_frame)
            button_frame.pack(side=ttk.LEFT, padx=5)

            for action_class in self.action_classes:
                button_text = getattr(action_class, 'title', lambda: "操作")()
                button = ttk.Button(button_frame, text=button_text,
                                    command=lambda i=row_index, ac=action_class: self.perform_action(i, ac))
                button.pack(side=ttk.LEFT, padx=5)

            # 绑定鼠标进入和离开事件
            item_frame.bind("<Enter>", lambda event, frame=item_frame: self.on_enter(frame))
            item_frame.bind("<Leave>", lambda event, frame=item_frame: self.on_leave(frame))

            # 设置数据行高
            if self.row_height is not None:
                item_frame.pack_propagate(0)
                item_frame.configure(height=self.row_height)

    def perform_action(self, index, action_class):
        data = self.data_model[index]
        new_window = ttk.Toplevel(self.root)
        new_window.title(getattr(action_class, 'window_title', "操作窗口"))
        form = action_class(new_window, data)

        # 窗口居中逻辑
        new_window.update_idletasks()
        width = new_window.winfo_width()
        height = new_window.winfo_height()
        x = (new_window.winfo_screenwidth() // 2) - (width // 2)
        y = (new_window.winfo_screenheight() // 2) - (height // 2)
        new_window.geometry(f"{width}x{height}+{x}+{y}")

    def perform_tool_action(self, tool_class):
        new_window = ttk.Toplevel(self.root)
        new_window.title(getattr(tool_class, 'window_title', "工具窗口"))
        form = tool_class(new_window)

        # 窗口居中逻辑
        new_window.update_idletasks()
        width = new_window.winfo_width()
        height = new_window.winfo_height()
        x = (new_window.winfo_screenwidth() // 2) - (width // 2)
        y = (new_window.winfo_screenheight() // 2) - (height // 2)
        new_window.geometry(f"{width}x{height}+{x}+{y}")

    def delete_item(self, index):
        del self.data_model[index]
        # 清空主框架内容
        for widget in self.main_frame.winfo_children():
            widget.destroy()
        # 重新创建表头和数据项
        self.setup_ui()

    def on_enter(self, frame):
        # 鼠标进入时改变背景颜色
        for child in frame.winfo_children():
            if isinstance(child, ttk.Label):
                child.configure(bootstyle="info")

    def on_leave(self, frame):
        # 鼠标离开时恢复默认背景颜色
        for child in frame.winfo_children():
            if isinstance(child, ttk.Label):
                child.configure(bootstyle="default")

    def get_main_frame(self):
        return self.main_frame